<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-sm12 layui-col-md12 layui-col-lg12">
            <div class="layui-card">
                <div class="layui-card-body">
                    <div class="layui-form toolbar">
                        <div class="layui-form-item">
                            <div class="layui-inline">
                                <input id="roleName" class="layui-input layui-input-inline" type="text" placeholder="角色名称"/>
                            </div>
                            <div class="layui-inline">
                                <button id="btnSearch" class="layui-btn layui-btn-sm icon-btn"><i class="layui-icon">&#xe615;</i>搜索</button>
                                <button id="btnExp" class="layui-btn layui-btn-sm icon-btn"><i class="layui-icon">&#xe67d;</i>导出</button>
                            </div>
                        </div>
                    </div>
                    <table id="SysRoleTable" lay-filter="SysRoleTable"></table>
                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/html" id="SysRoleTableToolBar">
    {php} if(in_array("admin/system.sysrole/add",session('menunames'))){ {/php}
    <a class="layui-btn layui-btn-normal layui-btn-sm " lay-event="add"><i class="layui-icon">&#xe654;</i>添加</a>
    {php} } {/php}
    {php} if(in_array("admin/system.sysrole/edit",session('menunames'))){ {/php}
    <a class="layui-btn layui-btn-normal layui-btn-sm" lay-event="edit"><i class="layui-icon">&#xe642;</i>修改</a>
    {php} } {/php}
    {php} if(in_array("admin/system.sysrole/delete",session('menunames'))){ {/php}
    <a class="layui-btn layui-btn-danger layui-btn-sm" lay-event="del"><i class="layui-icon">&#xe640;</i>删除</a>
    {php} } {/php}
    <button class="layui-btn layui-btn-sm layui-btn-radius" lay-event="expandAll"><i class="layui-icon">&#xe654;</i>展开所有</button>
    <button class="layui-btn layui-btn-sm layui-btn-radius" lay-event="foldAll"><i class="layui-icon">&#xe656;</i>折叠所有</button>
</script>
<script>
    var SysRoleRenderTable = function () {
        var loadingindex = layui.layer.msg('数据加载中...');
        var SysRoleTable = layui.treetable.render({
            treeColIndex: 3,          // treetable新增参数
            treeSpid: 0,             // treetable新增参数
            treeIdName: 'id',       // treetable新增参数
            treePidName: 'pid',     // treetable新增参数
            treeDefaultClose: false,   // treetable新增参数
            treeLinkage: true,        // treetable新增参数
            elem: '#SysRoleTable',
            url: '{:url("/admin/system.sysrole/index")}',
            method: "post",
            page: false,
            // skin: 'line',
            even: true, //开启隔行背景
            size: 'sm', //小尺寸的表格
            limit: '20',
            toolbar: "#SysRoleTableToolBar",
            defaultToolbar: ['filter', 'exports', 'print'],
            //defaultToolbar: [],
            loading: true,
            height: 'full-100',
            cellMinWidth: 100,
            cols: [[
                {type: 'radio'},
                {field: 'id', title: 'ID', width: 80},
                {field: 'pid', title: '父节点ID', width: 100},
                {
                    field: "title",
                    title: '角色名称',
                    width: 200, sort: false, filter: true
                },
                {
                    field: "menus",
                    title: '拥有权限',
                    align: 'left',
                    templet: function (d) {
                        var tempstr = [];
                        $.each(d.menus, function (index, item) {
                            tempstr.push(item.title);
                        });
                        return tempstr.join(',');
                    }
                },
                {
                    field: 'status', width: 80, align: 'center',
                    title: '状态', sort: true, filter: true,
                    templet: function (d) {
                        if (d.status == 1) {
                            return '<span class="layui-badge layui-bg-blue">启用</span>';
                        } else {
                            return '<span class="layui-badge-rim">禁用</span>';
                        }
                    }
                },
                {
                    field: "remark",
                    title: '备注',
                    align: 'center', sort: true, filter: true
                },
                {field: "", title: '操作', toolbar: "#operation", width: 220, fixed: 'right', align: 'center', hide: true},
            ]],
            done: function (res, curr, count) {
                layui.layer.close(loadingindex);
            }
        })
    }
    SysRoleRenderTable();
    layui.table.on('toolbar(SysRoleTable)', function (obj) {
        //console.log(obj);
        let data = layui.table.checkStatus(obj.config.id).data[0];
        //console.log(data);
        if (obj.event == 'add') {
            $.get('{:url("/admin/system.sysrole/edit")}', {}, function (str) {
                var indexlayer = layui.layer.open({
                    title: "添加",
                    offset: 't',
                    area: ['530px', '600px'],
                    shadeClose: true,
                    type: 1,
                    anim: parseInt(Math.random() * 6),
                    resize: false,
                    btn: ['保存', '取消'],
                    content: str,
                    yes: function (index, layero) {
                        //return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
                        var data = $("#roleForm").serializeObject();
                        //var param = dtree.getNowParam("parentIdTree");
                        var params = layui.dtree.getCheckbarNodesParam("dTree_nodeids");
                        //console.log(params);
                        var menuids = [];
                        $.each(params, function (index, item) {
                            menuids.push(item.nodeId);
                        });
                        data.menuids = menuids;
                        var dTree_pid_param = layui.dtree.getNowParam("dTree_pid");
                        data.pid = dTree_pid_param.nodeId;
                        $.ajax({
                            async: true,//默认true为异步
                            url: '{:url("/admin/system.sysrole/add")}',
                            type: "post",
                            data: data,
                            dataType: "json",
                            beforeSend: function (xhr) {
                            },
                            success: function (res, status, xhr) {
                                layer.msg(res.msg);
                                if (res.code == 1) {
                                    SysRoleRenderTable();
                                    layui.layer.close(indexlayer);
                                }
                            },
                            error: function (xhr, status, error) {
                            }
                        });
                    },
                    success: function (layero, index) {
                        yq_dtree('dTree_pid',{
                            url:'{:url("/admin/widget.sysrole/getAllList")}',
                            checkbar: false
                        },function(){
                        });
                        yq_dtree('dTree_nodeids',{
                            url:'{:url("/admin/widget.sysmenu/getAllList")}',
                            checkbar: true
                        },function(){
                        });
                    },
                    btn2: function (index, layero) {
                        //按钮【按钮二】的回调
                        //return false 开启该代码可禁止点击该按钮关闭
                    },
                    btn3: function (index, layero) {
                        //按钮【按钮三】的回调
                        //return false 开启该代码可禁止点击该按钮关闭
                    },
                    cancel: function () {
                        //右上角关闭回调
                        //return false 开启该代码可禁止点击该按钮关闭
                    }
                })
            });
        }
        if (obj.event == 'edit') {
            if (data != null) {
                $.get('{:url("/admin/system.sysrole/edit")}', {"id": data.id}, function (str) {
                    var indexlayer = layui.layer.open({
                        title: "修改",
                        offset: 't',
                        area: ['530px', '600px'],
                        shadeClose: true,
                        type: 1,
                        anim: parseInt(Math.random() * 6),
                        resize: false,
                        btn: ['保存', '取消'],
                        content: str,
                        yes: function (index, layero) {
                            //return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
                            var data = $("#roleForm").serializeObject();
                            //var param = dtree.getNowParam("parentIdTree");
                            var dTree_nodeids_params = layui.dtree.getCheckbarNodesParam("dTree_nodeids");
                            // console.log(params);
                            var menuids = [];
                            $.each(dTree_nodeids_params, function (index, item) {
                                menuids.push(item.nodeId);
                            });
                            data.menuids = menuids;
                            var dTree_pid_param = layui.dtree.getNowParam("dTree_pid");
                            data.pid = dTree_pid_param.nodeId;
                            $.ajax({
                                async: true,//默认true为异步
                                url: '{:url("/admin/system.sysrole/edit")}',
                                type: "post",
                                data: data,
                                dataType: "json",
                                beforeSend: function (xhr) {
                                },
                                success: function (res, status, xhr) {
                                    layer.msg(res.msg);
                                    if (res.code == 1) {
                                        SysRoleRenderTable();
                                        layui.layer.close(indexlayer);
                                    }
                                },
                                error: function (xhr, status, error) {
                                }
                            });
                        },
                        success: function (layero, index) {
                            var enhance = new layui.enhanceform({
                                elem: '#roleForm' //表单选择器
                            });
                            enhance.filling(data);//其中jsonData为表单数据的json对象
                            yq_dtree('dTree_pid',{
                                url:'{:url("/admin/widget.sysrole/getAllList")}',
                                checkbar: false
                            },function(){
                                layui.dtree.dataInit("dTree_pid", data.pid);
                                layui.dtree.selectVal("dTree_pid"); // 也可以在这里指定，第二个参数如果不填，则会自动读取
                            });
                            yq_dtree('dTree_nodeids',{
                                url:'{:url("/admin/widget.sysmenu/getAllList")}',
                                checkbar: true
                            },function(){
                                let ids = [];
                                $.each(data.menus, function (index, item) {
                                    ids.push(item.id);
                                });
                                layui.dtree.dataInit("dTree_nodeids", ids.join(','));
                                var params = layui.dtree.chooseDataInit("dTree_nodeids", ids.join(','));
                                layui.dtree.selectVal("dTree_nodeids"); // 也可以在这里指定，第二个参数如果不填，则会自动读取
                            });
                            layui.form.render();
                        },
                        btn2: function (index, layero) {
                            //按钮【按钮二】的回调
                            //return false 开启该代码可禁止点击该按钮关闭
                        },
                        btn3: function (index, layero) {
                            //按钮【按钮三】的回调
                            //return false 开启该代码可禁止点击该按钮关闭
                        },
                        cancel: function () {
                            //右上角关闭回调
                            //return false 开启该代码可禁止点击该按钮关闭
                        }
                    })
                });
            } else {
                layer.msg('请勾选记录！');
            }
        }
        if (obj.event == 'del') {
            if (data != null) {
                layui.layer.confirm('确定删除此信息？', {icon: 2, title: '提示信息'}, function (index) {
                    $.ajax({
                        type: "post",
                        url: '{:url("/admin/system.sysrole/delete")}',
                        data: {'id': data.id},
                        dataType: 'json',
                        success: function (d) {
                            layui.layer.msg("删除成功");
                            SysRoleRenderTable();
                        }
                    })
                    layer.close(index);
                });
            } else {
                layer.msg('请勾选记录！');
            }
        }
        if (obj.event == 'expandAll') {
            layui.treetable.expandAll('#SysRoleTable');
        }
        if (obj.event == 'foldAll') {
            layui.treetable.foldAll('#SysRoleTable');
        }
    });
</script>